package net.thetabx.ftdba.http;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;


import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.params.ClientPNames;
import org.apache.http.cookie.Cookie;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpParams;
import org.json.simple.JSONObject;

public class DefaultHttpManager implements HttpManager {
	private Boolean ready = false;
	private Boolean connected = false;
	
	private String protocol = "https://";
	private String baseUrl = "www.frenchtorrentdb.com";
	private DefaultHttpClient client = null;
	
	public DefaultHttpManager() {
		this.initHttpClient();
	}
	
	private void initHttpClient() {
		ready = true;
		client = new DefaultHttpClient();
	}
	
	public HttpData sendPost(String url, String[][] postData) {
		if(client == null)
			initHttpClient();
		if(url.indexOf("/") != 0)
			url = "/" + url;
		HttpPost postMethod = new HttpPost(protocol + baseUrl + url);
		ArrayList<NameValuePair> eList = new ArrayList<NameValuePair>();
		if(postData != null) {
			for(int i = 0; i < postData.length; i++) {
				eList.add(new BasicNameValuePair(postData[i][0], postData[i][1])); 
			}
			try {
				postMethod.setEntity(new UrlEncodedFormEntity(eList));
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		
		HttpParams params = postMethod.getParams();
		params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
		postMethod.setParams(params);
		
		HttpResponse response = null;
		try {
			response = client.execute(postMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new DefaultHttpData(response);
	}
	
	public HttpData sendGet(String url, String[][] getData) {
		if(client == null)
			initHttpClient();
		if(url.indexOf("/") != 0)
			url = "/" + url;
		String eList = "";
		if(getData != null) {
			for(int i = 0; i < getData.length; i++) {
				eList += "&" + getData[i][0] + "=" + getData[i][1];
			}
		}
		HttpGet getMethod = new HttpGet(protocol + baseUrl + url + eList);
		
		HttpParams params = getMethod.getParams();
		params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
		getMethod.setParams(params);
		
		HttpResponse response = null;
		try {
			response = client.execute(getMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new DefaultHttpData(response);
	}
	
	public InputStream download(String url) {
		if(client == null)
			initHttpClient();
		if(url.indexOf("/") != 0)
			url = "/" + url;
		String eList = "";
		HttpGet getMethod = new HttpGet(protocol + baseUrl + url + eList);
		
		HttpParams params = getMethod.getParams();
		params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
		getMethod.setParams(params);
		
		HttpResponse response = null;
		try {
			response = client.execute(getMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		try {
			return response.getEntity().getContent();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return null;
	}
	
	public HttpData send(String url) {
		return this.sendGet(url, null);
	}
	
	public void setSecure(Boolean secure) {
		if(secure)
			protocol = "https://";
		else
			protocol = "http://";
	}

	public void setCookie(String cookie) {
		BasicClientCookie c = new BasicClientCookie("WebsiteID", cookie);
		c.setDomain(".frenchtorrentdb.com");
		c.setExpiryDate(null);
		c.setPath("/");
		client.getCookieStore().addCookie(c);
	}
	
	public String getCookie() {
		List<Cookie> cookies = client.getCookieStore().getCookies();
		if(cookies == null)
			return null;
			
		for(Cookie cookie : cookies)
        {
            if(cookie.getName().equals("WebsiteID"))
            	return cookie.getValue();
        }
		return null;
	}
	
	public void destroyHttpClient() {
		ready = false;
		connected = false;
		if(client == null)
			return;
		client = null;
	}
	
	public Boolean isReady() {
		return ready;
	}
	
	public void setConnected(Boolean connected) {
		this.connected = connected;
	}
	
	public Boolean isConnected() {
		return connected;
	}
	
	public Boolean isProxified() {
		return false;
	}
	
	@SuppressWarnings("unchecked")
	public HttpData connect(String username, String password) {
		if(client == null)
			initHttpClient();
		HttpPost postMethod = new HttpPost(protocol + baseUrl + "/?section=LOGIN");
		
		JSONObject obj=new JSONObject();
		obj.put("username", username);
		obj.put("password", password);
		obj.put("secure_login", "");
		try {
			postMethod.setEntity(new StringEntity(obj.toJSONString()));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		HttpResponse response = null;
		try {
			response = client.execute(postMethod);
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return new DefaultHttpData(response);
	}
}
